package com.lixin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lixin.entity.Likes;
import com.lixin.exception.DuplicateLikeException;
import com.lixin.mapper.LikesMapper;
import com.lixin.service.ILikesService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用于存储动态的点赞记录 服务实现类
 * </p>
 *
 * @author lixin
 * @since 2023-07-28
 */
@Service
public class LikesServiceImpl extends ServiceImpl<LikesMapper, Likes> implements ILikesService {

    @Override
    public List<Likes> selectLikesByPostIds(List<Integer> postIds) {
        return this.lambdaQuery().in(Likes::getPostId, postIds).list();
    }

    @Override
    public Likes likePost(Integer postId, Integer userId) {
        if (hasLiked(postId, userId)) {
            throw new DuplicateLikeException();
        }
        Likes likes = new Likes();
        likes.setPostId(postId);
        likes.setUserId(userId);
        return addOrUpdate(likes);
    }


    @Override
    public Likes addOrUpdate(Likes likes) {
        if (likes.getLikeId() == null) {
            likes.setTimestamp(new Date());
            this.baseMapper.insert(likes);
        } else {
            this.baseMapper.updateById(likes);
        }
        return likes;
    }

    @Override
    public boolean hasLiked(Integer postId, Integer userId) {
        return this.lambdaQuery().eq(Likes::getUserId, userId).eq(Likes::getPostId, postId).one() != null;
    }
}
